<template>
  <div class="container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!--搜索区域-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model='queryInfo.query' :clearable="true" @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--数据表格-->
      <el-row>
        <el-col :span="24">
          <el-table
            :data="userList"
            stripe
            border
            style="width: 100%">
            <el-table-column label="#"
                             type="index"
                             width="50">
            </el-table-column>
            <el-table-column
              prop="username"
              label="姓名"
              width="180">
            </el-table-column>
            <el-table-column
              prop="email"
              label="邮箱"
              width="180">
            </el-table-column>
            <el-table-column
              prop="mobile"
              label="电话">
            </el-table-column>
            <el-table-column
              prop="role_name"
              label="角色">
            </el-table-column>
            <el-table-column
              prop="mg_state"
              label="状态"
            >
              <!--扩展插槽 scope.row获取行数据-->
              <template v-slot="scope">
                <el-switch
                  v-model="scope.row.mg_state"
                  @change="opStatus(scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              label="操作">
              <template v-slot="scope">
                <!--编辑用户信息-->
                <el-button type="primary" icon="el-icon-edit" size="medium"
                           @click="editUsers(scope.row.id)"></el-button>
                <!--删除用户信息-->
                <el-button type="danger" icon="el-icon-delete" size="medium"
                           @click="deleteUser(scope.row.id)"></el-button>
                <!--权限分配-->
                <el-tooltip content="权限分配" placement="top" :enterable="false">
                  <el-button type="primary" icon="el-icon-setting" size="medium" @click="setRight(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <!--分页部分-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>

          <!--新增用户弹窗-->
          <el-dialog
            title="新增用户"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="handleClose">
            <!--内容区-->
            <div>
              <el-form :model="newUserInfo" :rules="newUserInfoRules" ref="newUserInfo" label-width="70px"
                       class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="newUserInfo.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input v-model="newUserInfo.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="newUserInfo.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                  <el-input v-model="newUserInfo.mobile"></el-input>
                </el-form-item>
              </el-form>
            </div>
            <!--对话框操作区-->
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
          </el-dialog>

          <!--编辑用户弹窗-->
          <el-dialog
            title="编辑用户信息"
            :visible.sync="dialogEditVisible"
            width="30%"
            :close-on-click-modal="false"
            :before-close="handleClose">
            <!--内容区-->
            <div>
              <el-form :model="editUseInfo" :rules="editUseInfoRules" ref="editUseInfo" label-width="70px"
                       class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="editUseInfo.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="editUseInfo.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                  <el-input v-model="editUseInfo.mobile"></el-input>
                </el-form-item>
              </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="cancelEdit">取 消</el-button>
              <el-button type="primary" @click="updateUserInfo()">确 定</el-button>
            </span>
          </el-dialog>

          <!--分配权限对话框-->
          <el-dialog
            title="分配角色"
            :visible.sync="setRightsDialogVisible"
            width="30%"
            @close="closeSetRightDialogVisible"
          >
            <div class="user-info-box">
              <div class="item">当前用户名：{{userInfo.username}}</div>
              <div class="item">当前的角色：{{userInfo.role_name}}</div>
              <div class="item">分配新角色：
                <el-select v-model="selectRolesId" placeholder="请选择">
                <el-option
                  v-for="item in rolesList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select>
              </div>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="setRightsDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="confirmSetRight">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'users',
  data() {
    // 邮箱验证规则 自定义
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      //返回一个错误提示
      cb(new Error('请输入合法的邮箱'))
    };
    // 验证手机号的规则 自定义
    var checkMobil = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      //返回一个错误提示
      cb(new Error('请输入合法的手机号码'))
    };
    return {
      userList: [],
      // 请求参数
      queryInfo: {
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页显示几条数据
        pagesize: 10
      },
      // 新增用户信息
      newUserInfo: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 响应参数
      total: 0,
      // 新增用户弹窗
      dialogVisible: false,
      // 编辑用户
      dialogEditVisible: false,
      // 分配权限
      setRightsDialogVisible: false,
      // 待分配权限用户id
      userInfo: '',
      // 新增用户规则
      newUserInfoRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: checkMobil, trigger: 'blur'}
        ]
      },
      // 编辑用户信息规则
      editUseInfoRules: {
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: checkMobil, trigger: 'blur'}
        ]
      },
      editUseInfo: {
        "id": '',
        "username": '',
        "role_id": 0,
        "mobile": '',
        "email": ''
      },
      // 角色列表
      rolesList:[],
      // 选择角色id
      selectRolesId:''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const {data: res} = await this.$http.get('users', {params: this.queryInfo})
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 修改每页显示条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    // 修改显示第几页数据
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    async opStatus(val) {
      console.log(val);
      const {data: res} = await this.$http.put(`users/${val.id}/state/${val.mg_state}`)
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$message.error(res.meta.msg)
      }
      return this.$message.success('修改用户状态成功')
    },
    // 查询用户
    searchUser() {
      console.log('搜索的关键字是', this.queryInfo.query)
      this.getUserList()
    },
    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false
    },
    async addUser() {
      this.$refs.newUserInfo.validate(async (valid) => {
        if (!valid) return false
        const {data: res} = await this.$http.post('users', this.newUserInfo)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$refs.newUserInfo.resetFields()
        this.dialogVisible = false
        this.getUserList()
        this.$message.success('新增用户成功')
      })
    },
    async editUsers(userId) {
      this.dialogEditVisible = true
      const {data: res} = await this.$http.get(`users/${userId}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editUseInfo = res.data
      console.log('用户信息是', this.editUseInfo)
    },
    // 取消修改用户的编辑事件
    cancelEdit() {
      this.dialogEditVisible = false
      this.$refs.editUseInfo.resetFields()
    },
    // 修改用户数据
    async updateUserInfo() {
      this.$refs.editUseInfo.validate(async (valid) => {
        if (!valid) return false
        const {data: res} = await this.$http.put(`users/${this.editUseInfo.id}`, {
          email: this.editUseInfo.email,
          mobile: this.editUseInfo.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败！')
        }
        // 清除表单数据
        this.$refs.editUseInfo.resetFields()
        // 隐藏对话框
        this.dialogEditVisible = false
        // 提示修改结果
        this.$message.success('更新用户信息成功！')
        // 重新请求数据渲染
        this.getUserList()
      })
    },
    async deleteUser(id) {
      // 弹窗提示 确定 confirm 取消 cancel
      const deleteOp = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err)=>{
        return err
      })
      console.log('确认框提示', deleteOp)
      if(deleteOp !=='confirm'){
        return this.$message.info('已经取消删除')
      }
      const {data: res} = await this.$http.delete(`users/${id}`)
      if(res.meta.status !== 200) return this.$message.error('删除用户失败！')
      // 重新请求用户数据
      this.getUserList()
      // 删除操作结果
      this.$message.success('删除用户成功！')
    },
    // 获取用户id及显示弹窗
    async setRight(user) {
      console.log('分配权限', user.id)
      const {data: res} = await this.$http.get(`roles`)
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
      this.setRightsDialogVisible = true
      this.userInfo = user
    },
    async confirmSetRight(){
      if(!this.selectRolesId) return this.$message.error('请选择角色信息')
      const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`, {rid: this.selectRolesId})
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.setRightsDialogVisible = false
      this.getUserList()
      this.$message.success(res.meta.msg)
    },
    closeSetRightDialogVisible() {
      console.log('对话框关闭事件')
      // 关闭对话框前置空已选角色的id
      this.selectRolesId = ''
      // 关闭对话框前置空已选角色相关信息
      this.userInfo= {}
    }
  }
}
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}

.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, .15) !important;
}

.el-table {
  margin: 15px 0;
}
.item{
  padding: 10px 5px;
}
</style>
